<template>
  <view class="category-page">
    <!-- 顶部一级分类 -->
    <view class="top-category-bar">
      <scroll-view class="category-scroll" scroll-x="true">
        <view class="category-list">
          <view 
            class="top-category-item" 
            :class="{ active: activeTopCategory === item.id }"
            v-for="item in topCategoryList" 
            :key="item.id"
            @click="selectTopCategory(item)"
          >
            <image class="category-icon" :src="item.icon" mode="aspectFill"></image>
            <text class="category-name">{{ item.name }}</text>
          </view>
        </view>
      </scroll-view>
      <!-- 全部按钮 - 固定在右侧 -->
      <view class="all-category-btn-fixed" @click="showAllCategories">
        <text class="all-text">全部</text>
        <text class="expand-icon">▼</text>
      </view>
    </view>

    <!-- 全部分类弹出层 -->
    <view class="category-overlay" v-if="showCategoryOverlay" @click="hideAllCategories">
      <view class="category-popup" @click.stop>
        <view class="popup-header">
          <text class="popup-title">全部分类</text>
        </view>
        <view class="category-grid">
          <view 
            class="grid-category-item" 
            :class="{ active: activeTopCategory === item.id }"
            v-for="item in topCategoryList" 
            :key="item.id"
            @click="selectCategoryFromPopup(item)"
          >
            <image class="grid-category-icon" :src="item.icon" mode="aspectFill"></image>
            <text class="grid-category-name">{{ item.name }}</text>
          </view>
        </view>
        <view class="popup-footer">
          <view class="collapse-btn" @click="hideAllCategories">
            <text class="collapse-text">点击收起</text>
            <text class="collapse-icon">▲</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 主体内容区域 -->
    <view class="main-content">
      <!-- 左侧二级分类 -->
      <view class="subcategory-sidebar">
        <view 
          class="subcategory-item" 
          :class="{ active: activeSubCategory === item.id }"
          v-for="item in currentSubCategories" 
          :key="item.id"
          @click="selectSubCategory(item)"
        >
          <text class="subcategory-name">{{ item.name }}</text>
          <view class="new-tag" v-if="isNewCategory(item)">新</view>
        </view>
      </view>

      <!-- 右侧商品列表 -->
      <view class="product-content">
        <!-- 筛选栏 -->
        <view class="filter-bar">
          <view class="filter-tabs">
            <view 
              class="filter-tab" 
              :class="{ active: activeFilter === 'all' }"
              @click="setFilter('all')"
            >
              <text class="tab-text">全部</text>
            </view>
            <view 
              class="filter-tab" 
              :class="{ active: activeFilter === 'sales' }"
              @click="setFilter('sales')"
            >
              <text class="tab-text">销量</text>
            </view>
            <view 
              class="filter-tab" 
              :class="{ active: activeFilter === 'price' }"
              @click="setFilter('price')"
            >
              <text class="tab-text">价格</text>
              <text class="price-arrow">{{ priceOrder === 'asc' ? '▲' : '▼' }}</text>
            </view>
          </view>
        </view>

        <!-- 商品列表 -->
        <scroll-view class="product-list" scroll-y="true">
          <view class="product-item" v-for="(item, index) in filteredProductList" :key="index">
            <view class="product-image-wrapper">
              <image class="product-image" :src="getProductImage(item)" mode="aspectFill"></image>
              <view class="product-tag" v-if="getProductTag(item)">{{ getProductTag(item) }}</view>
            </view>
            <view class="product-info">
              <text class="product-title">{{ item.name }}</text>
              <text class="product-desc">{{ item.description }}</text>
              <view class="product-meta">
                <text class="delivery-info">{{ getDeliveryText(item.deliveryType) }}</text>
                <text class="sales-info" v-if="getSalesText(item)">{{ getSalesText(item) }}</text>
              </view>
              <view class="product-bottom">
                <text class="product-price">¥{{ getProductPrice(item) }}</text>
                <view class="add-cart-btn">
                  <text class="cart-icon">🛒</text>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 没有更多商品 -->
          <view class="no-more" v-if="filteredProductList.length > 0">
            <text class="no-more-text">没有更多商品啦</text>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      activeTopCategory: 'fruits', // 当前选中的一级分类
      activeSubCategory: 'new-fruits', // 当前选中的二级分类
      activeFilter: 'all', // 当前选中的筛选条件
      priceOrder: 'desc', // 价格排序方向
      showCategoryOverlay: false, // 控制全部分类弹出层显示
      
      // 默认一级分类数据（后续会从后端获取）
      topCategoryList: [
        {
          id: 'fruits',
          name: '果蔬鲜花',
          icon: '/static/images/category/fruits.png'
        },
        {
          id: 'dairy',
          name: '乳品烘焙',
          icon: '/static/images/category/dairy.png'
        },
        {
          id: 'grains',
          name: '粮油面点',
          icon: '/static/images/category/grains.png'
        },
        {
          id: 'meat',
          name: '肉禽蛋品',
          icon: '/static/images/category/meat.png'
        },
        {
          id: 'seafood',
          name: '海鲜水产',
          icon: '/static/images/category/seafood.png'
        },
        {
          id: 'appliances',
          name: '百货家电',
          icon: '/static/images/category/appliances.png'
        },
        {
          id: 'beverages',
          name: '酒水饮料',
          icon: '/static/images/category/beverages.png'
        },
        {
          id: 'snacks',
          name: '休闲零食',
          icon: '/static/images/category/snacks.png'
        },
        {
          id: 'beauty',
          name: '美妆个护',
          icon: '/static/images/category/beauty.png'
        },
        {
          id: 'baby',
          name: '婴宠保健',
          icon: '/static/images/category/baby.png'
        },
        {
          id: 'cleaning',
          name: '纸品清洁',
          icon: '/static/images/category/cleaning.png'
        },
        {
          id: 'gifts',
          name: '礼盒专区',
          icon: '/static/images/category/gifts.png'
        },
        {
          id: 'custom',
          name: '独家定制',
          icon: '/static/images/category/custom.png'
        }
      ],
      
      // 默认二级分类数据（后续会从后端获取）
      subCategoryData: {
        fruits: [
          { id: 'new-fruits', name: '新果上市', isNew: true },
          { id: 'coconut', name: '椰青/热带果' },
          { id: 'vegetables', name: '蔬菜' },
          { id: 'flowers', name: '鲜花' },
          { id: 'flower-tea', name: '花茶' }
        ],
        dairy: [
          { id: 'milk', name: '牛奶' },
          { id: 'yogurt', name: '酸奶' },
          { id: 'cheese', name: '奶酪' },
          { id: 'bread', name: '面包' },
          { id: 'cake', name: '蛋糕' }
        ],
        grains: [
          { id: 'rice', name: '大米' },
          { id: 'oil', name: '食用油' },
          { id: 'noodles', name: '面条' },
          { id: 'dumplings', name: '饺子' },
          { id: 'flour', name: '面粉' }
        ],
        meat: [
          { id: 'pork', name: '猪肉' },
          { id: 'beef', name: '牛肉' },
          { id: 'chicken', name: '鸡肉' },
          { id: 'eggs', name: '蛋品' },
          { id: 'duck', name: '鸭肉' }
        ],
        seafood: [
          { id: 'fish', name: '鱼类' },
          { id: 'shrimp', name: '虾类' },
          { id: 'crab', name: '蟹类' },
          { id: 'shellfish', name: '贝类' },
          { id: 'processed', name: '加工海鲜' }
        ],
        appliances: [
          { id: 'kitchen', name: '厨房电器' },
          { id: 'cleaning-appliances', name: '清洁电器' },
          { id: 'personal-care', name: '个护电器' },
          { id: 'home-appliances', name: '家居电器' }
        ],
        beverages: [
          { id: 'water', name: '饮用水' },
          { id: 'juice', name: '果汁饮料' },
          { id: 'tea', name: '茶饮料' },
          { id: 'coffee', name: '咖啡' },
          { id: 'alcohol', name: '酒水' }
        ],
        snacks: [
          { id: 'chips', name: '薯片' },
          { id: 'nuts', name: '坚果' },
          { id: 'candy', name: '糖果' },
          { id: 'chocolate', name: '巧克力' },
          { id: 'dried', name: '果干' }
        ],
        beauty: [
          { id: 'skincare', name: '护肤' },
          { id: 'makeup', name: '彩妆' },
          { id: 'haircare', name: '护发' },
          { id: 'bodycare', name: '身体护理' },
          { id: 'fragrance', name: '香水' }
        ],
        baby: [
          { id: 'baby-food', name: '婴儿食品' },
          { id: 'baby-care', name: '婴儿护理' },
          { id: 'baby-clothes', name: '婴儿服装' },
          { id: 'pet-food', name: '宠物食品' },
          { id: 'pet-care', name: '宠物护理' }
        ],
        cleaning: [
          { id: 'self-operated', name: '自营严选', isNew: true },
          { id: 'new-arrivals', name: '新品上市', isNew: true },
          { id: 'tissues', name: '面纸巾' },
          { id: 'toilet-paper', name: '卫生纸/湿厕纸' },
          { id: 'kitchen-paper', name: '厨房用纸' },
          { id: 'dehumidifier', name: '除湿/杀虫' },
          { id: 'cleaning-tools', name: '清洁工具' },
          { id: 'disposable', name: '一次性用品' },
          { id: 'laundry-pods', name: '洗衣凝珠' },
          { id: 'laundry-detergent', name: '洗衣液/粉' },
          { id: 'clothing-aids', name: '衣物助洁' },
          { id: 'disinfection', name: '消毒柔顺' }
        ],
        gifts: [
          { id: 'gift-boxes', name: '礼盒' },
          { id: 'gift-cards', name: '礼品卡' },
          { id: 'seasonal', name: '节日礼品' },
          { id: 'luxury', name: '高端礼品' },
          { id: 'custom-gifts', name: '定制礼品' }
        ],
        custom: [
          { id: 'personalized', name: '个性化定制' },
          { id: 'corporate', name: '企业定制' },
          { id: 'wedding', name: '婚礼定制' },
          { id: 'birthday', name: '生日定制' },
          { id: 'anniversary', name: '纪念日定制' }
        ]
      },
      
      // 商品数据（后续会从后端获取）
      productData: {}
    }
  },

  computed: {
    // 当前二级分类列表
    currentSubCategories() {
      return this.subCategoryData[this.activeTopCategory] || []
    },

    // 当前商品列表
    currentProductList() {
      return this.productData[this.activeSubCategory] || []
    },

    // 筛选后的商品列表
    filteredProductList() {
      let list = [...this.currentProductList]
      
      switch (this.activeFilter) {
        case 'sales':
          // 按销量排序（这里用价格模拟，后续会改为真实销量）
          list.sort((a, b) => b.price - a.price)
          break
        case 'price':
          // 按价格排序
          if (this.priceOrder === 'asc') {
            list.sort((a, b) => a.price - b.price)
          } else {
            list.sort((a, b) => b.price - a.price)
          }
          break
        default:
          // 全部，保持原有顺序
          break
      }
      
      return list
    }
  },

  onLoad(options) {
    // 如果有传入分类参数，则设置对应的分类
    if (options.topCategory) {
      this.activeTopCategory = options.topCategory
    }
    if (options.subCategory) {
      this.activeSubCategory = options.subCategory
    }
    
    // 初始化数据
    this.initData()
  },

  methods: {
    // 初始化数据
    async initData() {
      try {
        // 获取分类数据
        await this.loadCategoryData()
        // 获取商品数据
        await this.loadProductData()
      } catch (error) {
        console.error('初始化数据失败:', error)
        // 使用默认数据
        this.useDefaultData()
      }
    },

    // 加载分类数据
    async loadCategoryData() {
      // TODO: 调用后端接口获取分类数据
      // const response = await this.$http.get('/api/categories')
      // this.topCategoryList = response.data.topCategories
      // this.subCategoryData = response.data.subCategories
      console.log('加载分类数据')
    },

    // 加载商品数据
    async loadProductData() {
      // TODO: 调用后端接口获取商品数据
      // const response = await this.$http.get(`/api/products?categoryId=${this.activeSubCategory}`)
      // this.productData[this.activeSubCategory] = response.data
      console.log('加载商品数据')
    },

    // 使用默认数据
    useDefaultData() {
      console.log('使用默认数据')
      // 这里可以设置一些默认的商品数据用于测试
    },

    // 判断是否为新分类
    isNewCategory(category) {
      return category.isNew === true
    },

    // 获取商品图片（取第一张）
    getProductImage(product) {
      if (product.image_urls) {
        const images = product.image_urls.split(',')
        return images[0] || '/static/images/default-product.png'
      }
      return product.image_url || '/static/images/default-product.png'
    },

    // 获取商品标签
    getProductTag(product) {
      if (product.marketing_tag) {
        return this.getTagText(product.marketing_tag)
      }
      return null
    },

    // 标签文本映射
    getTagText(tagCode) {
      const tagMap = {
        1: '热销',
        2: '新品',
        3: '礼盒',
        4: '进口',
        5: '周年庆',
        6: '限时',
        7: '推荐',
        8: '特价'
      }
      return tagMap[tagCode] || null
    },

    // 获取商品价格（展示del_flag为0的sku价格）
    getProductPrice(product) {
      if (product.skus && product.skus.length > 0) {
        // 找到del_flag为0的sku（未删除的）
        const activeSku = product.skus.find(sku => sku.del_flag === '0')
        if (activeSku) {
          return activeSku.price
        }
      }
      return product.price || 0
    },

    // 获取配送文案
    getDeliveryText(deliveryType) {
      const deliveryMap = {
        1: '仅支持自提',
        2: '明日达',
        3: '隔日达',
        4: '当日达',
        5: '3-5日达',
        6: '7日达'
      }
      return deliveryMap[deliveryType] || '明日达'
    },

    // 获取销量文案（预留接口，目前用随机数）
    getSalesText(product) {
      // TODO: 后续从后端获取真实销量数据
      if (product.sales_count) {
        return `月${product.sales_count}+人已下单`
      }
      
      // 临时使用随机数
      const randomSales = Math.floor(Math.random() * 10000) + 100
      return `月${randomSales}+人已下单`
    },

    // 选择一级分类
    selectTopCategory(category) {
      this.activeTopCategory = category.id
      // 自动选择第一个二级分类
      const subCategories = this.currentSubCategories
      if (subCategories.length > 0) {
        this.activeSubCategory = subCategories[0].id
      }
      console.log('选择一级分类:', category.name)
      
      // 重新加载商品数据
      this.loadProductData()
    },

    // 选择二级分类
    selectSubCategory(category) {
      this.activeSubCategory = category.id
      console.log('选择二级分类:', category.name)
      
      // 重新加载商品数据
      this.loadProductData()
    },

    // 设置筛选条件
    setFilter(filter) {
      if (filter === 'price') {
        // 价格筛选：切换排序方向
        if (this.activeFilter === 'price') {
          this.priceOrder = this.priceOrder === 'asc' ? 'desc' : 'asc'
        } else {
          this.priceOrder = 'desc'
        }
      }
      
      this.activeFilter = filter
      console.log('设置筛选条件:', filter, '价格排序:', this.priceOrder)
    },

    // 显示全部分类弹出层
    showAllCategories() {
      this.showCategoryOverlay = true
      console.log('显示全部分类')
    },

    // 隐藏全部分类弹出层
    hideAllCategories() {
      this.showCategoryOverlay = false
      console.log('隐藏全部分类')
    },

    // 从弹出层选择分类
    selectCategoryFromPopup(category) {
      this.selectTopCategory(category)
      this.hideAllCategories()
    }
  }
}
</script>

<style scoped>
.category-page {
  height: 100vh;
  background-color: #f8f8f8;
  display: flex;
  flex-direction: column;
}

/* 顶部一级分类 */
.top-category-bar {
  background-color: #fff;
  border-bottom: 1rpx solid #f0f0f0;
  padding: 20rpx 0;
  position: relative;
}

.category-scroll {
  white-space: nowrap;
  padding-right: 120rpx; /* 为固定按钮留出空间 */
}

.category-list {
  display: flex;
  padding: 0 20rpx;
}

.top-category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 40rpx;
  min-width: 120rpx;
  transition: all 0.3s ease;
}

.top-category-item.active {
  color: #1BBC9B;
}

.category-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  margin-bottom: 10rpx;
}

.category-name {
  font-size: 24rpx;
  color: #333;
  text-align: center;
}

.top-category-item.active .category-name {
  color: #1BBC9B;
  font-weight: bold;
}

/* 全部按钮 - 固定在右侧 */
.all-category-btn-fixed {
  position: absolute;
  right: 20rpx;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 80rpx;
  transition: all 0.3s ease;
  padding: 15rpx 10rpx;
  border-radius: 20rpx;
  background-color: #f8f8f8;
  z-index: 10;
}

.all-category-btn-fixed:active {
  background-color: #e8e8e8;
}

.all-text {
  font-size: 24rpx;
  color: #333;
  text-align: center;
  margin-bottom: 5rpx;
}

.expand-icon {
  font-size: 20rpx;
  color: #666;
}

/* 全部分类弹出层 */
.category-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-top: 200rpx;
}

.category-popup {
  background-color: #fff;
  border-radius: 20rpx;
  width: 90%;
  max-height: 70vh;
  overflow: hidden;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.3);
}

.popup-header {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  text-align: center;
}

.popup-title {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
}

.category-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 30rpx;
  padding: 30rpx;
  max-height: 50vh;
  overflow-y: auto;
}

.grid-category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 10rpx;
  border-radius: 15rpx;
  transition: all 0.3s ease;
}

.grid-category-item.active {
  background-color: #f0fdfa;
}

.grid-category-item:active {
  background-color: #f0f0f0;
}

.grid-category-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  margin-bottom: 15rpx;
}

.grid-category-name {
  font-size: 24rpx;
  color: #333;
  text-align: center;
  line-height: 1.2;
}

.grid-category-item.active .grid-category-name {
  color: #1BBC9B;
  font-weight: bold;
}

.popup-footer {
  padding: 20rpx;
  border-top: 1rpx solid #f0f0f0;
  text-align: center;
}

.collapse-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 15rpx 30rpx;
  background-color: #f8f8f8;
  border-radius: 25rpx;
  transition: all 0.3s ease;
}

.collapse-btn:active {
  background-color: #e8e8e8;
}

.collapse-text {
  font-size: 28rpx;
  color: #666;
  margin-right: 10rpx;
}

.collapse-icon {
  font-size: 20rpx;
  color: #666;
}

/* 主体内容区域 */
.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 左侧二级分类 */
.subcategory-sidebar {
  width: 200rpx;
  background-color: #fff;
  border-right: 1rpx solid #f0f0f0;
  overflow-y: auto;
}

.subcategory-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 20rpx;
  border-bottom: 1rpx solid #f8f8f8;
  transition: all 0.3s ease;
  position: relative;
}

.subcategory-item.active {
  background-color: #f0fdfa;
  border-left: 6rpx solid #1BBC9B;
}

.subcategory-item:active {
  background-color: #f0f0f0;
}

.subcategory-name {
  font-size: 28rpx;
  color: #333;
  flex: 1;
}

.subcategory-item.active .subcategory-name {
  color: #1BBC9B;
  font-weight: bold;
}

.new-tag {
  background-color: #ff4757;
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  margin-left: 10rpx;
}

/* 右侧商品列表 */
.product-content {
  flex: 1;
  background-color: #fff;
  display: flex;
  flex-direction: column;
}

/* 筛选栏 */
.filter-bar {
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.filter-tabs {
  display: flex;
  gap: 40rpx;
}

.filter-tab {
  display: flex;
  align-items: center;
  padding: 10rpx 0;
  transition: all 0.3s ease;
}

.filter-tab.active {
  color: #1BBC9B;
}

.tab-text {
  font-size: 28rpx;
  color: #333;
}

.filter-tab.active .tab-text {
  color: #1BBC9B;
  font-weight: bold;
}

.price-arrow {
  font-size: 20rpx;
  color: #999;
  margin-left: 8rpx;
}

.filter-tab.active .price-arrow {
  color: #1BBC9B;
}

/* 商品列表 */
.product-list {
  flex: 1;
  padding: 20rpx;
}

.product-item {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f8f8f8;
}

.product-image-wrapper {
  position: relative;
  margin-right: 20rpx;
}

.product-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
}

.product-tag {
  position: absolute;
  top: 0;
  left: 0;
  background-color: #ff4757;
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-title {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
  margin-bottom: 10rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.product-desc {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.delivery-info {
  font-size: 22rpx;
  color: #1BBC9B;
}

.sales-info {
  font-size: 22rpx;
  color: #999;
  margin-right: 80rpx;
}

.product-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20rpx;
}

.product-price {
  font-size: 32rpx;
  color: #1BBC9B;
  font-weight: bold;
  flex: 1;
}

.add-cart-btn {
  width: 60rpx;
  height: 60rpx;
  background-color: #1BBC9B;
  border-radius: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  flex-shrink: 0;
  margin-right: 70rpx;
}

.add-cart-btn:active {
  transform: scale(0.9);
}

.cart-icon {
  font-size: 28rpx;
  color: #fff;
}

/* 没有更多商品 */
.no-more {
  text-align: center;
  padding: 40rpx 0;
}

.no-more-text {
  font-size: 24rpx;
  color: #999;
}
</style> 